package com.example.interviewassistant;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class InterviewQuestionsActivity extends AppCompatActivity {
    public static final String EXTRA_RESUME_TEXT = "resume_text";
    public static final String EXTRA_CONFIG = "config";
    
    private ListView lvQuestions;
    private ProgressBar progressBar;
    private TextView tvNoQuestions;
    private TextView tvStreamingResponse;
    private ScrollView scrollViewStreaming;
    
    private LlmApiService apiService;
    private QuestionItemAdapter questionsAdapter;
    private List<InterviewQuestion> questionsList = new ArrayList<>();

    private String resumeText;
    private QuestionGenerationConfig config;
    private boolean isGenerating = false;

    public static void start(Context context, String resumeText) {
        Intent intent = new Intent(context, QuestionConfigActivity.class);
        intent.putExtra(QuestionConfigActivity.EXTRA_RESUME_TEXT, resumeText);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interview_questions);

        lvQuestions = findViewById(R.id.lvQuestions);
        progressBar = findViewById(R.id.progressBar);
        tvNoQuestions = findViewById(R.id.tvNoQuestions);
        tvStreamingResponse = findViewById(R.id.tvStreamingResponse);
        scrollViewStreaming = findViewById(R.id.scrollViewStreaming);
        
        questionsAdapter = new QuestionItemAdapter(this, questionsList);
        lvQuestions.setAdapter(questionsAdapter);
        
        apiService = new LlmApiService();
        
        // 获取传递的数据
        resumeText = getIntent().getStringExtra(EXTRA_RESUME_TEXT);
        config = (QuestionGenerationConfig) getIntent().getSerializableExtra(EXTRA_CONFIG);
        
        if (config == null) {
            config = new QuestionGenerationConfig(); // 使用默认配置
        }
        
        // 打印接收到的配置信息，便于调试
        System.out.println("接收到的配置 - 问题数量: " + config.getQuestionCount());
        System.out.println("接收到的配置 - 难度级别: " + config.getDifficultyLevel());
        System.out.println("接收到的配置 - 技术领域: " + config.getSelectedDomains());
        
        if (resumeText != null && !resumeText.isEmpty()) {
            generateQuestions(resumeText, config);
        } else {
            showError("简历内容为空，无法生成问题");
        }
    }
    
    @Override
    protected void onDestroy() {
        // 确保在Activity销毁时取消任何正在进行的请求
        if (isGenerating && apiService != null) {
            apiService.cancelOngoingRequests();
        }
        super.onDestroy();
    }
    
    private void generateQuestions(String resumeText, QuestionGenerationConfig config) {
        // 显示加载状态
        showLoading(true);
        
        // 确保简历文本已经过脱敏处理
        String maskedResumeText = SensitiveDataMask.maskSensitiveInfo(resumeText);
        
        // 调用API服务生成问题
        apiService.generateInterviewQuestions(this, maskedResumeText, config, new LlmApiService.OnQuestionsGeneratedListener() {
            @Override
            public void onQuestionsGenerating(String partialResponse) {
                // 显示流式响应的实时结果
                showStreamingResponse(true, partialResponse);
            }
            
            @Override
            public void onQuestionsGenerated(List<InterviewQuestion> questions) {
                // 流式响应完成，显示最终问题列表
                isGenerating = false;
                questionsList.clear();
                questionsList.addAll(questions);
                questionsAdapter.notifyDataSetChanged();
                
                showLoading(false);
                showStreamingResponse(false, null);
                
                if (questions.isEmpty()) {
                    tvNoQuestions.setVisibility(View.VISIBLE);
                    lvQuestions.setVisibility(View.GONE);
                } else {
                    tvNoQuestions.setVisibility(View.GONE);
                    lvQuestions.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String errorMessage) {
                isGenerating = false;
                showError(errorMessage);
                showLoading(false);
                showStreamingResponse(false, null);
            }
        });
    }
    
    private void showStreamingResponse(boolean show, String response) {
        if (show && response != null) {
            tvStreamingResponse.setText(response);
            tvStreamingResponse.setVisibility(View.VISIBLE);
            scrollViewStreaming.setVisibility(View.VISIBLE);
            lvQuestions.setVisibility(View.GONE);
            tvNoQuestions.setVisibility(View.GONE);
            
            // 滚动到底部以显示最新内容
            scrollViewStreaming.post(() -> scrollViewStreaming.fullScroll(View.FOCUS_DOWN));
        } else {
            tvStreamingResponse.setVisibility(View.GONE);
            scrollViewStreaming.setVisibility(View.GONE);
        }
    }
    
    private void showLoading(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        
        if (isLoading) {
            lvQuestions.setVisibility(View.GONE);
            tvNoQuestions.setVisibility(View.GONE);
            tvStreamingResponse.setVisibility(View.GONE);
            scrollViewStreaming.setVisibility(View.GONE);
        }
    }
    
    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        tvNoQuestions.setText("无法生成问题: " + message);
        tvNoQuestions.setVisibility(View.VISIBLE);
        tvStreamingResponse.setVisibility(View.GONE);
        scrollViewStreaming.setVisibility(View.GONE);
        lvQuestions.setVisibility(View.GONE);
    }
} 